package com.it.config;

import com.it.filter.ValidateCodeFilter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author: CaoYouGen
 * @DateTime: 2023/11/09/10:21
 * @注释: TODO
 **/
@Configuration
@EnableGlobalMethodSecurity (prePostEnabled = true)
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ValidateCodeFilter validateCodeFilter;
    
    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    
    // 对密码进行编码
    @Bean
    public PasswordEncoder passwordEncoder () {
        return new BCryptPasswordEncoder();
    }
    
    
    @Override
    protected void configure (HttpSecurity http) throws Exception {
        // 配置登录之前添加一个验证码的过滤器
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class);
        // 配置路径拦截 的 url的匹配规则
        //所有请求，都需要认证
        http.authorizeRequests()
              .mvcMatchers("/code/image")
              .permitAll() //放开验证码的请求
              .anyRequest().authenticated();
        http.formLogin()
              .successHandler(myAuthenticationSuccessHandler)
              .loginPage("/login/toLogin") // 配置自定义的登录页面
              .usernameParameter("uname") // 指定登录页面的用户名字段
              .passwordParameter("pwd") // 指定登录页面的密码字段
              .loginProcessingUrl("/login/toLogin") // 配置点击登录时的请求的url
              .successForwardUrl("/index/toIndex") // 登录成功后跳转的页面
              .failureForwardUrl("/login/toLogin") // 登录失败后跳转的页面
              .permitAll();
        
        // 配置登出方式
        http.logout()
              .logoutUrl("/logout")
              .logoutSuccessUrl("/login/toLogin")
              .permitAll();
        //  禁用csrf跨域请求攻击
        http.csrf().disable();
    }
    
    
    /**
     * 资源服务匹配放行【静态资源文件】
     *
     * @param web
     * @throws Exception
     */
    // @Override
    //public void configure(WebSecurity web) throws Exception {
    //  web.ignoring().mvcMatchers("/resources/**");
    //}
    
}







